<template>
  <div class="space-y-4">
    <h2 class="text-xl font-semibold">自动填充</h2>

    <div class="grid grid-cols-1 lg:grid-cols-2 gap-4">
      <!-- 左侧：操作区 -->
      <div class="space-y-4">
        <!-- 选择模板 -->
        <div class="bg-white rounded-lg shadow p-4">
          <h3 class="text-lg font-medium mb-3">选择模板</h3>
          <select
            v-model="selectedTemplateId"
            @change="loadTemplate"
            class="w-full px-3 py-2 border rounded-lg"
          >
            <option value="">请选择模板</option>
            <option v-for="template in templates" :key="template.id" :value="template.id">
              {{ template.name }}
            </option>
          </select>
        </div>

        <!-- 批量OCR -->
        <div v-if="selectedTemplate" class="bg-white rounded-lg shadow p-4">
          <h3 class="text-lg font-medium mb-3">批量OCR识别</h3>
          
          <div v-if="materialsFolder" class="mb-3 p-2 bg-gray-50 rounded text-sm">
            <div class="flex justify-between">
              <span class="truncate">{{ materialsFolder }}</span>
              <button @click="clearMaterialsFolder" class="text-blue-600 ml-2">清除</button>
            </div>
          </div>
          
          <button
            @click="selectMaterialsFolder"
            :disabled="processing"
            class="w-full mb-3 px-4 py-2 bg-green-500 text-white rounded-lg disabled:bg-gray-400"
          >
            {{ materialsFolder ? '重新选择文件夹' : '选择材料文件夹' }}
          </button>
          
          <div v-if="materialsFolder" class="space-y-2">
            <label class="block text-sm">OCR模型</label>
            <select
              v-model="selectedModel"
              :disabled="processing"
              class="w-full px-3 py-2 border rounded-lg"
            >
              <option value="">请选择模型</option>
              <option v-for="model in ocrModels" :key="model.id" :value="model.id">
                {{ model.name }}
              </option>
            </select>
            
            <button
              @click="startBatchOCR"
              :disabled="processing || !selectedModel"
              class="w-full mt-2 px-4 py-2 bg-blue-500 text-white rounded-lg disabled:bg-gray-400"
            >
              {{ processing ? `识别中... (${ocrProgress.current}/${ocrProgress.total})` : '开始批量识别' }}
            </button>
            
            <div v-if="processing && ocrProgress.total > 0" class="mt-2">
              <div class="text-xs text-gray-600 mb-1">
                {{ ocrProgress.fileName }} ({{ ocrProgress.current }}/{{ ocrProgress.total }})
              </div>
              <div class="w-full bg-gray-200 rounded-full h-2">
                <div
                  class="bg-blue-500 h-2 rounded-full"
                  :style="{ width: `${(ocrProgress.current / ocrProgress.total) * 100}%` }"
                ></div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧：字段和预览 -->
      <div class="space-y-4">
        <!-- 模板字段列表 -->
        <div v-if="selectedTemplate" class="bg-white rounded-lg shadow">
          <div class="flex justify-between items-center p-4 border-b cursor-pointer" @click="showFields = !showFields">
            <h3 class="text-lg font-medium">模板字段</h3>
            <div class="flex items-center gap-2">
              <button
                v-if="!showFields"
                @click.stop="fillTemplate"
                :disabled="!canFill"
                class="px-4 py-2 bg-blue-500 text-white rounded-lg disabled:bg-gray-400 text-sm"
              >
                生成文档
              </button>
              <span class="text-gray-500">{{ showFields ? '▼' : '▶' }}</span>
            </div>
          </div>
          
          <div v-show="showFields" class="p-4">
            <div v-if="!selectedTemplate.variables || selectedTemplate.variables.length === 0" class="text-sm text-gray-500 py-4">
              该模板没有检测到变量
            </div>
            
            <div v-else class="space-y-2">
              <div
                v-for="variable in selectedTemplate.variables"
                :key="variable"
                class="p-2 border rounded"
                :class="fillData[variable] ? 'bg-green-50 border-green-300' : 'bg-gray-50'"
              >
                <label class="block text-sm font-medium mb-1">{{ variable }}</label>
                <input
                  v-model="fillData[variable]"
                  type="text"
                  class="w-full px-2 py-1 border rounded text-sm"
                  :placeholder="`请输入${variable}`"
                />
              </div>
            </div>
            
            <div v-if="showFields" class="mt-4">
              <button
                @click="fillTemplate"
                :disabled="!canFill"
                class="w-full px-4 py-2 bg-blue-500 text-white rounded-lg disabled:bg-gray-400"
              >
                生成文档
              </button>
            </div>
          </div>
        </div>

        <!-- OCR识别结果 -->
        <div v-if="batchOCRResult" class="bg-white rounded-lg shadow">
          <div class="flex justify-between items-center p-4 border-b cursor-pointer" @click="showOCRResult = !showOCRResult">
            <h3 class="text-lg font-medium">OCR识别结果</h3>
            <span class="text-gray-500">{{ showOCRResult ? '▼' : '▶' }}</span>
          </div>
          
          <div v-show="showOCRResult" class="p-4">
            <div class="text-sm space-y-1">
              <div>总计: {{ batchOCRResult.total }} 个文件</div>
              <div>成功: {{ batchOCRResult.success }} 个</div>
              <div>失败: {{ batchOCRResult.failed }} 个</div>
            </div>
            <div v-if="batchOCRResult.mergedData && Object.keys(batchOCRResult.mergedData).length > 0" class="mt-3 p-2 bg-gray-50 rounded text-xs max-h-40 overflow-y-auto">
              <div v-for="(value, key) in batchOCRResult.mergedData" :key="key" class="mb-1">
                <span class="font-medium">{{ key }}:</span> {{ value }}
              </div>
            </div>
          </div>
        </div>

        <!-- 预览结果 -->
        <div class="bg-white rounded-lg shadow">
          <div class="flex justify-between items-center p-4 border-b cursor-pointer" @click="showPreview = !showPreview">
            <h3 class="text-lg font-medium">预览结果</h3>
            <span class="text-gray-500">{{ showPreview ? '▼' : '▶' }}</span>
          </div>
          
          <div v-show="showPreview" class="p-4">
            <div v-if="previewContent" class="whitespace-pre-wrap p-3 bg-gray-50 rounded border text-sm max-h-60 overflow-y-auto">
              {{ previewContent }}
            </div>
            <div v-else class="text-center py-8 text-gray-400 text-sm">
              预览结果将显示在这里
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { templateAPI, fileAPI, fieldMappingAPI, batchOCRAPI, ocrAPI, configAPI } from '../api/app.js'

const templates = ref([])
const selectedTemplateId = ref('')
const selectedTemplate = ref(null)
const fillData = ref({})
const previewContent = ref('')

const materialsFolder = ref('')
const ocrModels = ref([])
const selectedModel = ref('')
const processing = ref(false)
const ocrProgress = ref({ current: 0, total: 0, fileName: '' })
const batchOCRResult = ref(null)

// 折叠面板状态
const showFields = ref(true)
const showOCRResult = ref(false)
const showPreview = ref(true)

const canFill = computed(() => {
  if (!selectedTemplate.value) return false
  if (!selectedTemplate.value.variables || !Array.isArray(selectedTemplate.value.variables)) return false
  return selectedTemplate.value.variables.every(v => fillData.value[v])
})

const loadTemplates = async () => {
  try {
    templates.value = await templateAPI.list()
  } catch (error) {
    console.error('加载模板失败:', error)
    alert('加载模板失败: ' + error.message)
  }
}

const loadOCRModels = async () => {
  try {
    ocrModels.value = await ocrAPI.getSiliconFlowModels()
    const config = await configAPI.get()
    if (config.ocrModelID) {
      selectedModel.value = config.ocrModelID
    }
  } catch (error) {
    console.error('加载OCR模型失败:', error)
  }
}

const selectMaterialsFolder = async () => {
  try {
    const folderPath = await batchOCRAPI.selectMaterialsFolder()
    if (folderPath) {
      materialsFolder.value = folderPath
    }
  } catch (error) {
    alert('选择文件夹失败: ' + error.message)
  }
}

const clearMaterialsFolder = () => {
  materialsFolder.value = ''
  batchOCRResult.value = null
}

const startBatchOCR = async () => {
  if (!materialsFolder.value || !selectedModel.value) {
    alert('请先选择材料文件夹和OCR模型')
    return
  }
  
  processing.value = true
  ocrProgress.value = { current: 0, total: 0, fileName: '' }
  
  try {
    const result = await batchOCRAPI.recognizeFolder(
      materialsFolder.value,
      selectedModel.value,
      (progress) => {
        ocrProgress.value = progress
      }
    )
    
    batchOCRResult.value = result
    
    if (result.mergedData && Object.keys(result.mergedData).length > 0) {
      await extractAndFillFields(result)
    }
    
    alert(`批量识别完成！成功: ${result.success}, 失败: ${result.failed}`)
  } catch (error) {
    console.error('批量OCR失败:', error)
    alert('批量OCR失败: ' + error.message)
  } finally {
    processing.value = false
    ocrProgress.value = { current: 0, total: 0, fileName: '' }
  }
}

const extractAndFillFields = async (ocrResult) => {
  if (!selectedTemplateId.value || !selectedTemplate.value) {
    return
  }
  
  try {
    let allText = ''
    if (ocrResult.results) {
      ocrResult.results.forEach(r => {
        if (r.text) {
          allText += r.text + '\n'
        }
      })
    }
    
    const extractedData = await batchOCRAPI.extractFieldsFromOCR(
      selectedTemplateId.value,
      ocrResult.mergedData || {},
      allText
    )
    
    Object.keys(extractedData).forEach(key => {
      if (selectedTemplate.value.variables && selectedTemplate.value.variables.includes(key)) {
        fillData.value[key] = extractedData[key]
      }
    })
    
    updatePreview()
  } catch (error) {
    console.error('提取字段失败:', error)
    if (ocrResult.mergedData) {
      Object.keys(ocrResult.mergedData).forEach(key => {
        if (selectedTemplate.value.variables && selectedTemplate.value.variables.includes(key)) {
          fillData.value[key] = ocrResult.mergedData[key]
        }
      })
      updatePreview()
    }
  }
}

const loadTemplate = async () => {
  if (!selectedTemplateId.value) {
    selectedTemplate.value = null
    fillData.value = {}
    previewContent.value = ''
    return
  }
  
  try {
    const result = await templateAPI.get(selectedTemplateId.value)
    selectedTemplate.value = JSON.parse(result)
    fillData.value = {}
    
    if (!selectedTemplate.value.variables) {
      selectedTemplate.value.variables = []
    }
    
    if (Array.isArray(selectedTemplate.value.variables)) {
      selectedTemplate.value.variables.forEach(v => {
        fillData.value[v] = ''
      })
    }
    
    updatePreview()
  } catch (error) {
    console.error('加载模板失败:', error)
    alert('加载模板失败: ' + error.message)
  }
}

const updatePreview = () => {
  if (!selectedTemplate.value) {
    previewContent.value = ''
    return
  }
  
  if (selectedTemplate.value.type === 'docx') {
    previewContent.value = 'DOCX 模板预览：填写数据后生成文档即可查看结果。\n\n已填充字段：\n'
    if (selectedTemplate.value.variables && Array.isArray(selectedTemplate.value.variables)) {
      selectedTemplate.value.variables.forEach(v => {
        const value = fillData.value[v] || '(未填写)'
        previewContent.value += `${v}: ${value}\n`
      })
    }
    return
  }
  
  let content = selectedTemplate.value.content || ''
  if (selectedTemplate.value.variables && Array.isArray(selectedTemplate.value.variables)) {
    selectedTemplate.value.variables.forEach(v => {
      const value = fillData.value[v] || `{{${v}}}`
      content = content.replace(new RegExp(`\\{\\{${v}\\}\\}`, 'g'), value)
    })
  }
  
  previewContent.value = content
}

const fillTemplate = async () => {
  if (!canFill.value) {
    alert('请填写所有必填项')
    return
  }
  
  try {
    const extension = selectedTemplate.value.type === 'docx' ? '.docx' : '.txt'
    const filename = `${selectedTemplate.value.name}_${Date.now()}${extension}`
    const filePath = await fileAPI.fillAndSave(
      selectedTemplateId.value,
      fillData.value,
      filename
    )
    
    try {
      await fileAPI.openFile(filePath)
    } catch (openError) {
      console.error('打开文件失败:', openError)
    }
    
    alert(`文档已生成：${filePath}`)
  } catch (error) {
    console.error('生成文档失败:', error)
    alert('生成文档失败: ' + error.message)
  }
}

const handleOCRResult = async (event) => {
  const ocrData = event.detail
  if (!selectedTemplate.value) return
  
  try {
    if (selectedTemplateId.value) {
      const mappedData = await fieldMappingAPI.apply(selectedTemplateId.value, ocrData)
      Object.keys(mappedData).forEach(key => {
        fillData.value[key] = mappedData[key]
      })
    } else {
      if (selectedTemplate.value.variables && Array.isArray(selectedTemplate.value.variables)) {
        Object.keys(ocrData).forEach(key => {
          if (selectedTemplate.value.variables.includes(key)) {
            fillData.value[key] = ocrData[key]
          }
        })
      }
    }
    updatePreview()
  } catch (error) {
    console.error('应用字段映射失败:', error)
    if (selectedTemplate.value.variables && Array.isArray(selectedTemplate.value.variables)) {
      Object.keys(ocrData).forEach(key => {
        if (selectedTemplate.value.variables.includes(key)) {
          fillData.value[key] = ocrData[key]
        }
      })
      updatePreview()
    }
  }
}

watch(fillData, () => {
  updatePreview()
}, { deep: true })

onMounted(() => {
  loadTemplates()
  loadOCRModels()
  window.addEventListener('ocr-result-ready', handleOCRResult)
})

onUnmounted(() => {
  window.removeEventListener('ocr-result-ready', handleOCRResult)
})
</script>
